package it.univaq.di.helpdesk.business.common.impl.ibatis.util;

import java.sql.SQLException;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

public class IBATISBooleanHandlerCallback implements TypeHandlerCallback {
	private static final int YES = 1;
	private static final int NO = 0;

	@Override
	public Object getResult(ResultGetter getter) throws SQLException {
		int status = getter.getInt();
		if (YES == status) {
		  return new Boolean (true);
		} else if (NO == status) {
		  return new Boolean (false);
		} else {
		  throw new SQLException (
		    "Unexpected value " + status + " found where " + YES + " or " + NO + " was expected.");
		}
	}

	@Override
	public void setParameter(ParameterSetter setter, Object parameter)
			throws SQLException {
		boolean b = ((Boolean)parameter).booleanValue();
		if (b) {
		  setter.setInt(YES);
		} else {
		  setter.setInt(NO);
		}
	}

	@Override
	public Object valueOf(String s)  {
		if (YES == Integer.parseInt(s)) {
			return new Boolean (true);
		} else if (NO == Integer.parseInt(s)) {
		    return new Boolean (false);
		}
		
		return null;
	}
}
